package cn.com.cdb.ldms.modules.system.components;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class AutoViewConfigProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        // 扫描所有Controller类
        ClassPathScanningCandidateComponentProvider scanner =
                new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(Controller.class));
        scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class));

        // 遍历所有Controller类的方法
        scanner.findCandidateComponents("*").forEach(beanDefinition -> {
            try {
                Class<?> clazz = Class.forName(beanDefinition.getBeanClassName());
                for (Method method : clazz.getMethods()) {
                    AutoViewConfig annotation = method.getAnnotation(AutoViewConfig.class);
                    if (annotation != null) {
                        // 动态注册子控制器Bean
                        registerDynamicController(registry, method, annotation);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed to process @AutoViewConfig", e);
            }
        });
    }

    private void registerDynamicController(BeanDefinitionRegistry registry,
                                           Method originalMethod,
                                           AutoViewConfig config) {
        // 获取类路径和方法路径
        String[] classPaths = PathUtils.getClassPaths(originalMethod.getDeclaringClass());
        String[] methodPaths = PathUtils.getMethodPaths(originalMethod);

        // 拼接完整路径（处理多个斜杠）
        String fullPath = Stream.of(classPaths[0], methodPaths[0], config.pathSuffix())
                .filter(s -> !s.isEmpty())
                .collect(Collectors.joining("/"))
                .replaceAll("//+", "/");

        // 获取HTTP方法（优先使用AutoViewConfig配置的方法）
        RequestMethod requestMethod = Optional.ofNullable(config.method())
                .orElseGet(() -> Arrays.stream(originalMethod.getAnnotations())
                        .map(PathUtils::getMethodType)
                        .filter(Objects::nonNull)
                        .findFirst()
                        .orElse(RequestMethod.GET));

        // 创建动态控制器的Bean定义
        BeanDefinitionBuilder builder = BeanDefinitionBuilder
                .rootBeanDefinition(DynamicControllerFactory.class)
                .addConstructorArgValue(fullPath)
                .addConstructorArgValue(requestMethod)
                .addConstructorArgValue(config)
                .setFactoryMethod("createDynamicController");

        // 注册Bean
        String beanName = originalMethod.getDeclaringClass().getSimpleName().toLowerCase() + "Config";
        registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
    }
}